from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import Constant as C
import json
import requests
import os
import subprocess
import shutil

def writeInitISConfig():
    '''
    写ISpider的初始化配置文件
    :return:
    '''
    conurl = 'https://gitee.com/ruxia-tjy/ispider/raw/master/config.json'
    r = requests.get(conurl)
    if r.status_code == 200:
        with open('config.json','w',encoding='utf-8') as f:
            f.write(r.text)

def getNewsTxt():
    rDict = {'status':False}
    try:
        url = 'https://gitee.com/ruxia-tjy/ispider/raw/master/%E6%9B%B4%E6%96%B0%E6%97%A5%E5%BF%97.txt'

        r = requests.get(url)
        if r.status_code == 200:
            with open('更新日志.txt','w',encoding='utf-8') as f:
                f.write(r.text)
                rDict['status'] = True
    except Exception as e:
        rDict['error'] = e
    return rDict

def changeConfig(key,value):
    with open('config.json','r',encoding='utf-8') as f:
        j = json.loads(f.read())

    j[key] = value
    j = json.dumps(j,ensure_ascii=False)
    with open('config.json','w',encoding='utf-8') as f:
        f.write(j)

def getWebPluginList():
    '''
    获取服务器上的插件列表
    :return:
    '''
    rDict = {}
    try:
        r = requests.get('https://gitee.com/ruxia-tjy/ispiderplugin/raw/master/pluginlist.json')
        if r.status_code == 200:
            rDict = {'status':True,'data':r.text}
        else:
            rDict ={'status':False,'error':f"无法连接到服务器！错误代码:{r.status_code}"}
    except:
        rDict = {'status':False,"error":"无法连接到服务器！"}

    return rDict

def isVersion1After2(version1,version2):
    '''
    判断版本1是否后于版本2
    :param version1:
    :param version2:
    :return:
    '''

    version1 = [int(i) for i in version1.split('.')]
    version2 = [int(i) for i in version2.split('.')]

    return version1 > version2

def isPluginWebVersionAfterLocal(name,webversion):
    '''
    判断插件服务器版本是否高于本地版本
    :param name:
    :param webversion:
    :return:
    '''
    with open(f'Plugin/{name}/config.plc','r',encoding='utf-8') as f:
        j = json.loads(f.read())

    return isVersion1After2(webversion,j['版本'])

def checkISpiderUpdate(localVersion):
    '''
    检查ISpider是否可以更新
    :param localVersion:
    :return:
    '''
    url = 'https://gitee.com/ruxia-tjy/ispider/raw/master/config.json'
    r = requests.get(url)
    webversion = json.loads(r.text)['版本']

    return isVersion1After2(webversion,localVersion)

def downloadPlugin(name):
    '''
    下载插件
    :param name:插件名称
    :return:
    '''
    rDict = {'status':False}
    try:
        # 删除原有的
        if os.path.exists(f'Plugin/{name}'):
            shutil.rmtree(f'Plugin/{name}')
        os.mkdir(f'Plugin/{name}')

        # 获取信息
        r = getWebPluginList()

        if r['status'] == True:
            j = json.loads(r['data'])
            for i in range(len(j["插件"])):
                if j['插件'][i]['名称'] == name:
                    rDict['data'] = j['插件'][i]

                    for item in j['插件'][i]['下载文件']:
                        r = requests.get(requests.utils.quote(j['插件'][i]['下载文件'][item]).replace('%3A',':'),stream=True)

                        if r.status_code == 200:

                            C.downloadDict[f'{name}下载'] = 0
                            if r.headers['Content-Type'] == 'application/octet-stream':
                                max = int(r.headers['Content-Length'])
                                change = 102400 / max
                                with open(f"Plugin/{name}/{item}",'wb') as f:
                                    for chunk in r.iter_content(chunk_size=1024):
                                        f.write(chunk)
                                        C.downloadDict[f'{name}下载'] += change
                            else:
                                with open(f"Plugin/{name}/{item}",'wb') as f:
                                    f.write(r.content)

                    pluginConfig = json.dumps(j['插件'][i], ensure_ascii=False)
                    with open(f'Plugin/{name}/config.plc', 'w', encoding='utf-8') as f:
                        f.write(pluginConfig)
                        del pluginConfig
                    rDict['status']=True
                    break
        else:
            rDict= {'status':False,'error':f'{r["error"]}'}
    except Exception as e:
        rDict = {'status':False,'error':e}

    if name in C.downloadDict['名称']:
        C.downloadDict['名称'].remove(name)
    return rDict

def msgbox(title,text,*btn):
    rtxt = 'Y'
    msgbox = QMessageBox()
    msgbox.setWindowTitle(title)
    msgbox.setText(text)
    l = len(btn)
    if l == 0:
        msgbox.setStandardButtons(QMessageBox.Yes)
        btnY = msgbox.button(QMessageBox.Yes)
        btnY.setText("确定")
        msgbox.exec_()
    elif l == 1:
        msgbox.setStandardButtons(QMessageBox.Yes)
        btnY = msgbox.button(QMessageBox.Yes)
        btnY.setText(btn[0])
        msgbox.exec_()
    elif l == 2:
        msgbox.setStandardButtons(QMessageBox.Yes|QMessageBox.No)
        btnY = msgbox.button(QMessageBox.Yes)
        btnY.setText(btn[0])
        btnN = msgbox.button(QMessageBox.No)
        btnN.setText(btn[1])
        msgbox.exec_()

        if msgbox.clickedButton() == btnN:
            rtxt = 'N'

    elif l == 3:
        msgbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
        btnY = msgbox.button(QMessageBox.Yes)
        btnY.setText(btn[0])
        btnN = msgbox.button(QMessageBox.No)
        btnN.setText(btn[1])
        btnC = msgbox.button(QMessageBox.Cancel)
        btnC.setText(btn[2])
        msgbox.exec_()

        if msgbox.clickedButton() == btnN:
            rtxt = 'N'
        elif msgbox.clickedButton() == btnC:
            rtxt = 'C'

    return rtxt

def runPlugin(name):
    rDict = {'status':False}
    try:
        with open(f'Plugin/{name}/config.plc','r',encoding='utf-8') as f:
            j = json.loads(f.read())

        PluginRunPath = os.path.join(f'Plugin/{name}',j['启动程序'])

        workdir = os.path.join('data', name)

        if not os.path.exists(workdir):
            os.mkdir(workdir)

        p = subprocess.Popen(PluginRunPath,
                             shell=False,
                             cwd=workdir)
        while True:
            p.poll()
            if p.returncode != None:
                break
        rDict['status'] = True
    except Exception as e:
        rDict = {'status':False,'error':e}

    C.runLst.remove(name)
    return rDict


def deletePlugin(name):
    rDict = {'status':False}
    try:
        if os.path.exists(f'Plugin/{name}'):
            shutil.rmtree(f'Plugin/{name}')
            rDict['status'] = True
    except Exception as e:
        rDict = {'status':False,'error':e}
    return rDict
